package com.zhou.common.quartz.test.quartz.jobclass;

import com.zhou.base.components.bs.common.exception.base.BaseExceptionBuilder;
import com.zhou.common.quartz.test.task.TestAsyncService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.scheduling.quartz.QuartzJobBean;

/**
 * @author xianfeng
 * @date 2023/12/20 21:46
 * @description:
 */
@Slf4j
@RequiredArgsConstructor
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class MySampleJob extends QuartzJobBean {

    private final TestAsyncService asyncService;

    // fields ...
    private Integer index;

    // Inject the "name" job data property
    public void setIndex(Integer index) {
        this.index = index;
    }

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        JobKey jobKey = context.getJobDetail().getKey();
        //getMergedJobDataMap 是不能持久化的
        //JobDataMap mergedJobDataMap = context.getMergedJobDataMap();
        //            mergedJobDataMap.put("index", 2);
        //getTrigger().getJobDataMap() 是不能持久化的
        //JobDataMap triggerJobData = context.getTrigger().getJobDataMap();
        //triggerJobData.put("index", 2);
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        log.info("开始执行job,jobkey={},param.index={}", jobKey, index);

//        Future<String> stringFuture = asyncService.testAsync1();
        try {
            if (index == 1) {
                throw BaseExceptionBuilder.message("测试抛出异常");
            }
            jobDataMap.put("index", index + 1);

//            log.info("jobkey={},执行定时任务的结果={}", jobKey, stringFuture.get());
            log.info("jobkey={},执行定时任务的结果={}", jobKey, "231");
        } catch (Exception e) {
            //不需要在这里打印异常，系统会打印JobExecutionException的同事打印出这里的e
            log.info("--- Error in job!");
            JobExecutionException e2 = new JobExecutionException(e);
            //修改传递的参数，以便下次可以正确
            //这份工作会被立即执行,立即执行是在当前线程执行,
            // context已经初始化，mergedJobDataMap也被初始化了
            //这个时候可以修改参数
            e2.setRefireImmediately(true);
            context.getMergedJobDataMap().put("index", index + 1);
            //当前的这次执行会被放弃，等待下次执行
//            e2.setRefireImmediately(false);
            throw e2;
        }
    }
}


